﻿using mozhi.smarterp.Finance.Basedatas.Events;
using mozhi.smarterp.Finance.Enums;
using System;
using System.Collections.Generic;
using Volo.Abp;

namespace mozhi.smarterp.Finance.Accounts
{
    /// <summary>
    /// 科目核算维度
    /// </summary>
    public class AccountDimension : AggregateRootBase<Guid>
    {
        /// <summary>
        /// 编码
        /// </summary>
        public string Code { private set; get; }

        /// <summary>
        /// 名称
        /// </summary>
        public string Name { private set; get; }

        /// <summary>
        /// 数据来源
        /// </summary>
        public DataSourceType DataSourceType { private set; get; }

        /// <summary>
        /// 标签
        /// </summary>
        public Guid? TagId { private set; get; }

        public AccountDimension(Guid id, string code, string name, DataSourceType dataSourceType , bool activated)
        {
            Id = id;
            Code = code;
            Name = name;
            DataSourceType = dataSourceType;
            Activated = activated;

            Validate();

            if (TagId.HasValue)
                AddDistributedEvent(new DataAssociationAddEvent(Id, nameof(AccountDimension), "核算维度", Code, Name, TagId.Value, "Tag"));
        }

        private void Validate()
        {
            var messages = new List<string>();

            if (Code.IsNullOrEmpty())
                messages.Add("编码为必填项");


            if (Name.IsNullOrEmpty())
                messages.Add("名称为必填项");

            if (DataSourceType == default)
                messages.Add("数据来源为必填项");

            if (messages.Count > 0)
                throw new UserFriendlyException(string.Join(",", messages), "100000");
        }

        public void Change(string code ,string name)
        {
            this.Code = code;
            this.Name = name;

            Validate();
        }

        public void ChangeType(DataSourceType sourceType, Guid? tagId)
        {
            var oldTagId = TagId;

            if (sourceType == DataSourceType.Tag && !tagId.HasValue)
                throw new UserFriendlyException("数据来源为标签时，标签不能能为空", "100000");

            DataSourceType = sourceType;

            TagId = DataSourceType == DataSourceType.Tag ? tagId : null;

            if (oldTagId != TagId)
            {
                if (oldTagId.HasValue)
                    AddDistributedEvent(new DataAssociationRemoveEvent(Id, oldTagId.Value));

                if (TagId.HasValue)
                    AddDistributedEvent(new DataAssociationAddEvent(Id, nameof(AccountDimension), "核算维度", Code, Name, TagId.Value, "Tag"));
            }

        }

        /// <summary>
        /// 更改状态
        /// </summary>
        /// <param name="activated"></param>
        public void ChangeStatus(bool activated)
        {
            this.Activated = activated;
        }
    }
}
